<?php
namespace App\Logic\SalesAmazon;

use App\Models\Product\ProductAmazonSku;
use App\Models\SalesAmazon\SalesAmountDay;
use Illuminate\Support\Facades\DB;
class Sales2AmountDaily
{
    public static function init()
    {
        $num = 810;
        $i = 611;
        while(true){
            if($i > $num)break;
            $time = strtotime("-{$i} days");
            $day = date('Ymd',$time);
            DB::beginTransaction();
            try{
                $sku = [];
                SalesAmountDay::query()->where('day',$day)
                    ->orderBy('id')
                    ->chunk(500, function ($items) use(&$sku){
                        foreach ($items as $item){
                            if($item->psku_id != 0)continue;
                            if(!array_key_exists($item->seller_sku,$sku)){
                                $pSkuId = ProductAmazonSku::query()->where('seller_sku',$item->seller_sku)->value('psku_id');
                                $sku[$item->seller_sku] = $pSkuId ?: 0;
                            }
                            $item->psku_id = $sku[$item->seller_sku];
                            $item->save();
                        }
                    });
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
            $i++;
            sleep(10);
        }
    }
}
